package edu.zjut.hjg.saas.biz.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import edu.zjut.hjg.saas.biz.dao.UserLogDao;
import edu.zjut.hjg.saas.biz.model.UserLog;
import edu.zjut.hjg.saas.biz.support.Paginated;

public class UserLogDaoImpl extends SqlMapClientDaoSupport implements UserLogDao {

    @Override
    public Integer create(UserLog userLog) {
        return (Integer) getSqlMapClientTemplate().insert("userLog.create", userLog);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Paginated<UserLog> listByAppId(int appId, int pageSize, int page) {
        Map<String, Object> params = new HashMap<String, Object>();
        Integer totalSize = (Integer) getSqlMapClientTemplate().queryForObject(
                "userLog.countByAppId", appId);
        int start = pageSize * (page - 1);
        if (start > totalSize) {
            start = (totalSize / pageSize) * pageSize;
        }
        params.put("appId", appId);
        params.put("pageSize", pageSize);
        params.put("start", start);
        List<UserLog> list = getSqlMapClientTemplate().queryForList("userLog.listByAppId", params);
        Paginated<UserLog> paginated = new Paginated<UserLog>();
        paginated.setValues(list);
        paginated.setPageSize(pageSize);
        paginated.setStart(start);
        paginated.setTotalSize(totalSize);
        return paginated;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<UserLog> listFreshByLimit(int limit) {
        return getSqlMapClientTemplate().queryForList("userLog.listFreshByLimit", limit);
    }
}
